// pages/index/recharge/recharge.js
let app = getApp()
import drawQrcode from '../../../utils/weapp.qrcode.min.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    win_height: '',
    qrcode_bg:'../../../images/qrcode_bg.png',
    stroge_qrcode_bg:'',
    qrcode_src:'',
    qrcode_image:'',
    last_qrcode_image:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let qrcode_ = wx.getStorageSync('qrcode_money');
    console.log(qrcode_);
    that.setData({
      win_height: app.globalData.winHeight,
      qrcode_src:qrcode_
    })
    that.draw_canvas(that);
  },

  /**
   * 绘图
   * **/
  draw_canvas:function(that_){
    let screen_width = wx.getSystemInfoSync().screenWidth;
    let scale = screen_width / 750;
    drawQrcode({
      width: 360 * scale,
      height: 360 * scale,
      canvasId: 'mycanvas',
      // ctx: wx.createCanvasContext('myQrcode'),
      text: that_.data.qrcode_src,
      callback:function(e){
        setTimeout(() => {
          console.log(e);
          wx.canvasToTempFilePath({
            //通过id 指定是哪个canvas
            canvasId: 'mycanvas',
            success(res) {
              console.log(res)
              that_.setData({
                qrcode_image: res.tempFilePath
              })
              //调用绘图
              that_.drawCanvasFun()
            }
          })
        },1500)
      }
    })
  },

  /**
   * 开始绘制
   * **/
  drawCanvasFun:function(){
    let that = this;
    const context = wx.createCanvasContext('activityCanvas', this)
    //绘制背景url,x,y,w,h
    context.drawImage(that.data.qrcode_bg,0,0,256.8,330.2)
    //绘制二维码
    context.drawImage(that.data.qrcode_image, 50.9, 82, 155, 155)
    context.draw()
    //生成图片
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'activityCanvas',
        success: function (res) {
          console.log(res)
          let canvasImgSrc = res.tempFilePath
          that.setData({
            last_qrcode_image: canvasImgSrc
          });
        },
        fail: function (err) {
          console.log(err)
        }
      }, that)
    }, 2000)
  },

  /**
   * 保存二维码
   * **/
  save_qrcode_btn:function(){
    let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.last_qrcode_image,
      success: function (res) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})